package com.chookss.home.running;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.RunningChoiceEntity;
import com.chookss.home.entity.RunningRankEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BasisTimesUtils;
import com.chookss.view.BottomRunningChoiceDialog;
import com.chookss.view.CircleImageView;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.SelectRunningDialogListener;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

public class RunningRankActivity extends BaseAct {
//活动排行榜列表

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.llChoice)
    LinearLayout llChoice;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.rlType)
    RelativeLayout rlType;
    @BindView(R.id.rvType)
    RecyclerView rvType;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.tvChoice)
    TextView tvChoice;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.tvRank)
    TextView tvRank;
    @BindView(R.id.ivRank)
    ImageView ivRank;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.bottom_ll)
    LinearLayout bottom_ll;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout common_right_iv_ll;
    @BindView(R.id.bottomShadow)
    ImageView bottomShadow;
    private RunningRankAdapter adapter;
    private List<RunningRankEntity> list = new ArrayList<>();
    private List<RunningChoiceEntity> runningChoiceEntityList = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private String createTime, orgCode, activityCode, activityName, groupCode;
    private ArrayList<String> typeList = new ArrayList<>();
    private BottomRunningChoiceDialog bottomListsDialog = null;
    private int searchType=1;//1当日2累计
    private String statusCd = "2";  //statusCd 1未开始2进行中3已结束
    private boolean isDelay=false;//是否需要延迟
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_running_rank);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        activityCode = getIntent().getStringExtra("activityCode");
        activityName = getIntent().getStringExtra("activityName");
        createTime = getIntent().getStringExtra("createTime");
        statusCd = getIntent().getStringExtra("statusCd");
        if(!Utils.isNull(createTime)){
            isDelay=true;
        }
        if("3".equals(statusCd)){
            //已结束的活动默认展示累计的数据
            searchType=2;
            createTime=Utils.getCurrentTime2().substring(0, 10);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new RunningRankAdapter(R.layout.item_running_rank, this, list);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        commonTitleTxt.setText("排行榜");
        tvNone.setText("暂无数据");
        if (!Utils.isNull(activityName)) {
            tvChoice.setText("活动");
            common_right_iv_ll.setVisibility(View.VISIBLE);
            llChoice.setVisibility(View.GONE);
        }
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                if(isDelay){
                    //此情况只允许刚进来的时候出现一次
                    isDelay=false;
                    Observable.timer(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) {
                                    getData();
                                    getSingleData();
                                }
                            });
                }else{
                    getData();
                    getSingleData() ;
                }
            }
        });
        typeList.add("全部");
        typeList.add("部门");
        typeList.add("项目组");
        typeList.add("活动");
        rvType.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvType.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        TypeAdapter adapter = new TypeAdapter(R.layout.item_looklog_type, this, typeList);
        rvType.setAdapter(adapter);
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        if (!Utils.isNull("createTime")) {
            map.put("createTime", createTime);
        }
        if (!Utils.isNull("orgCode")) {
            map.put("orgCode", orgCode);
        }
        if (!Utils.isNull("activityCode")) {
            map.put("activityCode", activityCode);
        }
        if (!Utils.isNull("groupCode")) {
            map.put("groupCode", groupCode);
        }
        map.put("searchType", searchType+"");//1当日2累计
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RunningRankEntity>>>() {
        }.getType(), null, Urls.selectMoveLvlListByDay, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RunningRankEntity>>() {
            @Override
            public void onSuccess(List<RunningRankEntity> data) {

                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                int old = list.size();
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                        MyToast.show("暂无数据");
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getSingleData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", "1");
        map.put("pageSize", "1");
        if (!Utils.isNull("createTime")) {
            map.put("createTime", createTime);
        }
        if (!Utils.isNull("orgCode")) {
            map.put("orgCode", orgCode);
        }
        if (!Utils.isNull("activityCode")) {
            map.put("activityCode", activityCode);
        }
        if (!Utils.isNull("groupCode")) {
            map.put("groupCode", groupCode);
        }
        map.put("searchType", searchType+"");//1当日2累计
        map.put("employeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RunningRankEntity>>>() {
        }.getType(), null, Urls.selectMyMoveLvl, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RunningRankEntity>>() {
            @Override
            public void onSuccess(List<RunningRankEntity> data) {
                if (bottom_ll == null) {
                    return;
                }
                if (data.size() == 0) {
                    bottom_ll.setVisibility(View.GONE);
                    bottomShadow.setVisibility(View.GONE);
                    return;
                }
                RunningRankEntity entity = data.get(0);
                if (Utils.isNull(entity.getHeadPhotoThumbUrl())) {
                    bottom_ll.setVisibility(View.GONE);
                    bottomShadow.setVisibility(View.GONE);
                } else {
                    bottom_ll.setVisibility(View.VISIBLE);
                    bottomShadow.setVisibility(View.VISIBLE);
                    GlideUtils.loadAvatar(RunningRankActivity.this, entity.getHeadPhotoThumbUrl(), ivHead);
                    tvName.setText(entity.getEmployeeName());
                    tvNum.setText(Utils.changeNumber(entity.getMoveNum()) + "");
                    int num = Utils.changeNumber(entity.getRankNum());
                    if (num > 3) {
                        tvRank.setVisibility(View.VISIBLE);
                        ivRank.setVisibility(View.GONE);
                        tvRank.setText(num + "");
                    } else {
                        ivRank.setVisibility(View.VISIBLE);
                        tvRank.setVisibility(View.GONE);
                        if (num == 1) {
                            Glide.with(RunningRankActivity.this).load(R.drawable.paiming_one).into(ivRank);
                        } else if (num == 2) {
                            Glide.with(RunningRankActivity.this).load(R.drawable.paiming_two).into(ivRank);
                        } else if (num == 3) {
                            Glide.with(RunningRankActivity.this).load(R.drawable.paiming_three).into(ivRank);
                        } else {
                            tvRank.setVisibility(View.VISIBLE);
                            ivRank.setVisibility(View.GONE);
                            tvRank.setText("   ");
                        }
                    }
                }

            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    class RunningRankAdapter extends BaseQuickAdapter<RunningRankEntity, BaseViewHolderEx> {
        private Activity context;

        public RunningRankAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<RunningRankEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, RunningRankEntity entity) {
            LinearLayout llBg = helper.getView(R.id.llBg);
            TextView tvRank = helper.getView(R.id.tvRank);
            ImageView ivRank = helper.getView(R.id.ivRank);
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvNum = helper.getView(R.id.tvNum);
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            GlideUtils.loadAvatar(context, entity.getHeadPhotoThumbUrl(), ivHead);
            tvName.setText(entity.getEmployeeName());
            tvNum.setText(Utils.changeNumber(entity.getMoveNum()) + "");
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) llBg.getLayoutParams();
            if (helper.getItemPosition() == 0) {
                params.setMargins(0, Utils.dip2px(RunningRankActivity.this, 19), 0, 0);
            } else {
                params.setMargins(0, 0, 0, 0);
            }
            llBg.setLayoutParams(params);
            tvRank.setText(entity.getRankNum() + "");
            if (helper.getItemPosition() > 2) {
                tvRank.setVisibility(View.VISIBLE);
                ivRank.setVisibility(View.GONE);
            } else {
                int num = Utils.changeNumber(entity.getRankNum());
                if (helper.getItemPosition() == 0) {
                    ivRank.setVisibility(View.VISIBLE);
                    tvRank.setVisibility(View.GONE);
                    Glide.with(RunningRankActivity.this).load(R.drawable.paiming_one).into(ivRank);
                } else if (helper.getItemPosition() == 1) {
                    if (num == 1) {
                        tvRank.setVisibility(View.VISIBLE);
                        ivRank.setVisibility(View.GONE);
                    } else {
                        ivRank.setVisibility(View.VISIBLE);
                        tvRank.setVisibility(View.GONE);
                        Glide.with(RunningRankActivity.this).load(R.drawable.paiming_two).into(ivRank);
                    }
                } else if (helper.getItemPosition() == 2) {
                    if (num == 1 || num == 2) {
                        tvRank.setVisibility(View.VISIBLE);
                        ivRank.setVisibility(View.GONE);
                    } else {
                        ivRank.setVisibility(View.VISIBLE);
                        tvRank.setVisibility(View.GONE);
                        Glide.with(RunningRankActivity.this).load(R.drawable.paiming_three).into(ivRank);
                    }
                }
            }
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(context, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", entity.getEmployeeCode());
                    context.startActivity(intent);
                }
            });
        }
    }

    class TypeAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;

        public TypeAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable ArrayList<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView tvType = helper.getView(R.id.tvType);
            tvType.setText(entity);
            tvType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rlType.setVisibility(View.GONE);
                    ivChoice.setBackgroundResource(R.drawable.small_arrow_down_20);
                    if (helper.getItemPosition() == 0) {
                        orgCode = "";
                        activityCode = "";
                        groupCode = "";
                        tvChoice.setText(entity);
                        smrRf.autoRefresh();
                    } else if (helper.getItemPosition() == 1) {
                        getOrgCode();
                    } else if (helper.getItemPosition() == 2) {
                        getGroupList();
                    } else {
                        getActivitys();
                    }

                }
            });
        }
    }

    private void showBottomDialog(int type) {
        bottomListsDialog = new BottomRunningChoiceDialog(this, runningChoiceEntityList, new SelectRunningDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onListItemClick(int position, List<RunningChoiceEntity> list) {
                if (type == 0) {
                    orgCode = list.get(position).getEmployeeCode();
                    tvChoice.setText("部门");
                    activityCode = "";
                    groupCode = "";
                } else if (type == 1) {
                    groupCode = list.get(position).getGroupCode();
                    tvChoice.setText("项目组");
                    orgCode = "";
                    activityCode = "";
                } else if (type == 2) {
                    if(list.get(position).getStatusCd().equals("1")){
                        MyToast.show("活动暂未开始，敬请期待");
                        return;
                    }
                    activityCode = list.get(position).getActivityCode();
                    tvChoice.setText("活动");
                    orgCode = "";
                    groupCode = "";
                }
                searchType=1;
                smrRf.autoRefresh();
            }
        });
        bottomListsDialog.show();
    }

    private void getOrgCode() {
        //部门基本数据
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", "1");
        map.put("pageSize", "100");
//        if(Utils.isNull(source)){
//            //不需要权限，可以查看所有人
//            map.put("type", "0");
//        }else{
        //需要权限，只能查看下属的
        map.put("type", "1");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RunningChoiceEntity>>>() {
        }.getType(), null, Urls.selectOrgAndEmpByCode, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RunningChoiceEntity>>() {
            @Override
            public void onSuccess(List<RunningChoiceEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvChoice == null) {
                        return;
                    }
                    runningChoiceEntityList.clear();
                    runningChoiceEntityList.addAll(data);
                    for (int i = 0; i < data.size(); i++) {
                        runningChoiceEntityList.get(i).setChoiceType(0);
                    }
                    showBottomDialog(0);
                } else {
                    MyToast.show("暂无部门");
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RunningChoiceEntity>>>() {
        }.getType(), null, Urls.selectMyItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<RunningChoiceEntity>>() {
            @Override
            public void onSuccess(List<RunningChoiceEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvChoice == null) {
                        return;
                    }
                    runningChoiceEntityList.clear();
                    runningChoiceEntityList.addAll(data);
                    for (int i = 0; i < data.size(); i++) {
                        runningChoiceEntityList.get(i).setChoiceType(1);
                    }
                    showBottomDialog(1);
                } else {
                    MyToast.show("暂无项目组");
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getActivitys() {
        //活动基本数据
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", "1");
        map.put("pageSize", "100");
        map.put("searchType", "1");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RunningChoiceEntity>>>() {
        }.getType(), null, Urls.selectMoveInfoList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<RunningChoiceEntity>>() {
            @Override
            public void onSuccess(List<RunningChoiceEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvChoice == null) {
                        return;
                    }
                    runningChoiceEntityList.clear();
                    runningChoiceEntityList.addAll(data);
                    for (int i = 0; i < data.size(); i++) {
                        runningChoiceEntityList.get(i).setChoiceType(2);
                    }
                    showBottomDialog(2);
                } else {
                    MyToast.show("暂无参与的活动");
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.rlType, R.id.llChoice, R.id.common_right_iv_ll})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llChoice:
            case R.id.rlType:
                if (rlType == null) {
                    return;
                }
                if (rlType.getVisibility() == View.VISIBLE) {
                    rlType.setVisibility(View.GONE);
                    ivChoice.setBackgroundResource(R.drawable.small_arrow_down_20);
                } else {
                    rlType.setVisibility(View.VISIBLE);
                    ivChoice.setBackgroundResource(R.drawable.small_arrow_up_20);
                }
                break;
            case R.id.common_right_iv_ll:
                showDatePickDialog();
                break;
        }
    }

    int mYear = 0, mMonth = 0, mDay = 0;
    String monthS = "", dayS = "";

    private void showDatePickDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mYear == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog2(this, true, "请选择日期", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener2() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        setDate(2, year, month, dayOfMonth);
                    }

                    @Override
                    public void onCancel(int year, int month, int dayOfMonth) {
                        setDate(1, year, month, dayOfMonth);
                    }
                }).setDay(0);
    }

    private void setDate(int tag, int year, int month, int dayOfMonth) {
        searchType=tag;
        mYear = year;
        mMonth = month - 1;
        mDay = dayOfMonth;
        if (commonTitleTxt == null) {
            return;
        }
        if (dayOfMonth > 9) {
            dayS = dayOfMonth + "";
        } else {
            dayS = "0" + dayOfMonth;
        }
        if (month > 9) {
            monthS = month + "";
        } else {
            monthS = "0" + month;
        }
        createTime = year + "-" + monthS + "-" + dayS;
        smrRf.autoRefresh();
    }
}
